#include "toolsclientserver.h"

ToolsCSReturn send_ToolsCS(int socket, const char *message)
{
  ssize_t sendT;
  sendT = send(socket, message, strlen(message)*sizeof(char), 0);
  if(sendT == -1 && errno == EMSGSIZE)
    {
      size_t sizeMsg;
      size_t sendMsg;
      char *tmp;
      ToolsCSReturn ret;
      sizeMsg = strlen(message);
      sendMsg = sizeMsg / 2;
      tmp = (char *) malloc (sendMsg * sizeof(char));
      strncpy(tmp, message, sendMsg);
      ret = send_ToolsCS(socket, tmp);
      free(tmp);
      if(ret == TOOLSCSRETURN_ERR)
	return ret;
      tmp = (char *) malloc (strlen(&message[sendMsg + 1]) * sizeof(char));
      strcpy(tmp, &message[sendMsg + 1]);
      ret = send_ToolsCS(socket, tmp);
      free(tmp);
      if(ret == TOOLSCSRETURN_ERR)
	return ret;
    }
  else if(sendT == -1)
    return TOOLSCSRETURN_ERR;
  return TOOLSCSRETURN_SUCCESS;
}

ToolsCSReturn receive_ToolsCS(char **reception, int socket)
{
  char tRecv;
  char *tJumpLine = NULL;
  char *tmp = NULL;
  ssize_t sizeRecv = 0;
  char iErr = 0;
  do
    {
      sizeRecv = recv(socket, &tRecv, sizeof(char), 0);
      if(sizeRecv == -1)
	{
	  /* Erreur de reception sur la socket */
	  fprintf(stderr, "[receive_ToolsCS]Erreur réception %d\n", socket);
	  return TOOLSCSRETURN_ERR;
	}
      if(sizeRecv == 0)
	{
	  fprintf(stderr, "[receive_ToolsCS]Erreur réception 0 octet socket %d\n", socket);
	  if((*reception) == NULL)
	    return TOOLSCSRETURN_ERR;
	  else 
	    {
	      if (iErr == 0)
	      sizeRecv = 1;
	      iErr ++;
	    }
	  /* On réessaye 1 fois */
	}
      else if((*reception) == NULL)
	{
	  (*reception) = (char *) malloc ((sizeRecv + 1) * sizeof(char));
	  strncpy((*reception), &tRecv, sizeRecv);
	  (*reception)[sizeRecv] = '\0';
	}
      else
	{
	  tmp = (char *) malloc ((sizeRecv + strlen((*reception)) + 1) * sizeof(char));
	  sprintf(tmp, "%s%c", (*reception), tRecv);
	  /*
	  strcpy(tmp, (*reception));
	  strncat(tmp, &tRecv, sizeRecv);
	  tmp[strlen((*reception)) + sizeRecv] = '\0';
	  */
	  free((*reception));
	  (*reception) = tmp;
	  tmp = NULL;
	}
    }while(sizeRecv != 0 && (tJumpLine = strchr((*reception), '\n')) == NULL);
  if(tJumpLine == NULL)
    return TOOLSCSRETURN_ERR;
  tJumpLine[0] = '\0';
  tJumpLine = strchr((*reception), '\r');
  if(tJumpLine != NULL)
    tJumpLine[0] = '\0';
  return TOOLSCSRETURN_SUCCESS;
}
